package com.xingxue.rbac.dao.impl;

import com.xingxue.rbac.dao.OrgDao;
import com.xingxue.rbac.entity.Module;
import com.xingxue.rbac.entity.Org;
import com.xingxue.rbac.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yihang
 */
public class OrgDaoImpl implements OrgDao {
    @Override
    public List<Org> findAll() {
        String sql = "SELECT a.ID, a.NAME, a.PID FROM RBAC_ORG a";
        Connection conn;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtil.getConnection();
            psmt = conn.prepareStatement(sql);
            rs = psmt.executeQuery();
            List<Org> list = new ArrayList<>();
            while (rs.next()) {
                list.add(rsToOrg(rs));
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(rs, psmt);
        }
    }

    private Org rsToOrg(ResultSet rs) throws SQLException {
        Org org = new Org();
        org.setId(rs.getInt("ID"));
        org.setName(rs.getString("NAME"));
        org.setPid(rs.getInt("PID"));
        return org;
    }
}
